/**
 * Created by zachary on 2017/7/3.
 */

(function(win, undefined){
  if(!win.weixinUtil) {
    win.weixinUtil = {}
  }

  win.weixinUtil.appid = {
    test: 'wx5945db57462199d4',
    prod: 'wx555f0f5c1b85cdf9'
  }

  function isTest() {
    return /-t/g.test(window.location.hostname);
  }

  function getUrlParam(name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = win.location.search.substr(1).match(reg);
    if (r!=null) return unescape(r[2]); return null;
  }

  win.weixinUtil.hasAuthorized = function() {
    var wxcode = getUrlParam('code');
    return wxcode ? true : false;
  }

  win.weixinUtil.authorize = function() {
    var search = JSON.parse('{' + (location.search.match(/[\w\%]+=[^\&\=]+/g) || []).map(function(value) {
      return '"' + value + '"'
    }).join(',').replace(/=/g, '":"') + '}');

    var searchStr = '?'

    for(var key in search) {
      if(key != 'code' && key != 'state') {
        searchStr += key + '=' + search[key] + '&'
      }
    }

    searchStr = searchStr.substring(0, searchStr.length - 1);

    if(localStorage) {
      var authNum = parseInt(localStorage.getItem('authNum') || 0) + 1
      localStorage.setItem('authNum', authNum)
    }

    var href =  location.origin + location.pathname + searchStr;
    var uri = encodeURIComponent(href);
    var appid = isTest() ? weixinUtil.appid.test : weixinUtil.appid.prod;
    var reLink = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+uri+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
    location.href = reLink;

    return false;
  }

  win.weixinUtil.inviteCodeBinding = function(options) {
    if(!options || !options.invitationCode || !options.code) {
      console.log('inviteCodeBinding options param error:', options)
      return;
    }
    XT.jsonp({
      url: XT.interface.api('/auth/h5/dis-invite-register'),
      data: {
        invitationCode:options.invitationCode,
        code: options.code,
        inviterUserId: options.inviterUserId || ''
      },
      jsonpCallback: 'disInviteRegister',
      super_success: function (data) {
        options.super_success && options.super_success(data);
      },
    })
  }

  win.weixinUtil.pay = function(options, callback) {
    options = options || {};

    // wx.chooseWXPay({
    //   appId:options.appId,     //公众号名称，由商户传入
    //   timestamp:options.timeStamp, //时间戳，自1970年以来的秒数
    //   nonceStr:options.nonceStr, //随机串
    //   package:options.package,
    //   signType:options.signType || "MD5", //微信签名方式：
    //   paySign:options.paySign, //微信签名
    //   success: function(res) {
    //     callback && callback(res);
    //   }
    // })
    //
    // wx.error(function(res){
    //   callback && callback(res.err_msg);
    //   return false;
    // });


    WeixinJSBridge.invoke(
      'getBrandWCPayRequest', {
        "appId":options.appId,     //公众号名称，由商户传入
        "timeStamp":options.timeStamp, //时间戳，自1970年以来的秒数
        "nonceStr":options.nonceStr, //随机串
        "package":options.package,
        "signType":options.signType || "MD5", //微信签名方式：
        "paySign":options.paySign //微信签名
      },
      function(res){
        //get_brand_wcpay_request:ok	支付成功
        //get_brand_wcpay_request:cancel	支付过程中用户取消
        //get_brand_wcpay_request:fail	支付失败
        // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        // XT.debug(res, true);
        if(res.err_msg == "get_brand_wcpay_request:ok" ) {
          callback && callback('ok');
        }else if (res.err_msg ==  "get_brand_wcpay_request:cancel") {
          callback && callback('cancel');
        }else if (res.err_msg ==  "get_brand_wcpay_request:fail") {
          callback && callback(res.err_desc || 'fail');
        }else {
          callback && callback(res.err_msg || res.errMsg || res.err_desc);
        }
      }
    );
  }


})(window, undefined)